#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<string.h>


#define NUM 1024
#define SIZE 32
#define SEP " "


char cmd_line[NUM];
char*g_argv[SIZE];

int main()
{
  while(1)
  {
    printf("[root@localhost mysheel]#");
    fflush(stdout);

    memset(cmd_line,0,sizeof cmd_line);
    if(fgets(cmd_line,sizeof cmd_line,stdin)==NULL)continue;
    cmd_line[strlen(cmd_line)-1]='\0';
    //procrintf("%s\n",cmd_line);
    
    g_argv[0]=strtok(cmd_line,SEP);
    int index=1;
    if(strcmp(g_argv[0],"ll")==0)
    {
      g_argv[0]="ls";
      g_argv[index++]="-l";
    }
    
    if(strcmp(g_argv[0],"ls")==0)
    {
      g_argv[index++]="--color=auto";

    }
    while(g_argv[index++]=strtok(NULL,SEP));
    //int i=0;
    //for(i=0;g_argv[i];i++)printf("g_argv[%d]:%s\n",i,g_argv[i]);
    
    //内置命令
    if(strcmp(g_argv[0],"cd")==0&&g_argv[1]!=NULL)chdir(g_argv[1]);//cd命令
    if(strcmp(g_argv[0],"export")==0&&g_argv[1]!=NULL)
    {
      int ret=putenv(g_argv[1]);//环境变量
      if(ret==0)printf("export success:%s\n",g_argv[1]);
      printf("putenv:%s\n",getenv("wlh"));
      continue;
    } 
    pid_t id=fork();
    if(id==0)
    {
      printf("child do:\n");
      execvp(g_argv[0],g_argv);
      exit(1);
    }
    int status=0;
    pid_t ret=waitpid(id,&status,0);
    if(ret>0)
    {
      printf("exit code:%d\n",WEXITSTATUS(status));
    }
  }
}
